Java 您所在的位置:网站首页 java excel 转 pdf Java

Java

#Java| 来源: 网络整理| 查看: 265

😊 @ 作者: 一恍过去 💖 @ 主页: https://blog.csdn.net/zhuocailing3390 🎊 @ 社区: Java技术栈交流 🎉 @ 主题: Java-Aspose实现上传Excel、Word转换为PDF并进行下载 ⏱️ @ 创作时间: 2022年04月23日

在这里插入图片描述

目录 前言1、加载Aspose包2、配置license2、word转pdf3、excel转pdf

前言

Aspose.Words 是一个用于 Java 平台的强大的文档处理库,它允许开发人员在他们的 Java 应用程序中创建、编辑、转换和呈现 Word 文档。以下是 Aspose.Words 的一些主要功能和用途:

创建和编辑 Word 文档:Aspose.Words 提供了一套丰富的 API,可以创建新的 Word 文档并对其进行编辑。您可以添加和格式化文本、插入表格、插入图片和其他图形,设置页面布局和格式等。文档转换:Aspose.Words 允许您将 Word 文档转换为其他常见的文件格式,如 PDF、HTML、纯文本、图像等。同样,您也可以将其他格式的文档转换为 Word 格式。模板处理:Aspose.Words 支持使用模板来创建和填充 Word 文档。您可以将模板与数据源结合使用,动态生成包含可变内容的文档,例如合同、报告和邮件。文档操作:Aspose.Words 提供了丰富的功能来处理文档,如提取文本、插入页眉和页脚、合并和拆分文档、查找和替换文本等。格式化和样式:您可以使用 Aspose.Words 设置字体、段落和表格的格式,应用样式和主题,控制页眉和页脚,创建目录和索引等。

本文使用 Aspose 来实现 Excel、Word转换为PDF,基本流程如下:

使用Aspose.Cells包来处理Excel 文档,将 Excel 文档转换为 PDF。 Workbook workbook = new Workbook(inputFilePath);workbook.save(outputFilePath, SaveFormat.PDF); 使用Aspose.Words包来处理Word 文档将 Word 文档转换为 PDF。 Document doc = new Document(inputFilePath);doc.save(outputFilePath, SaveFormat.PDF); 1、加载Aspose包

1、下载: Aspose官网没有提供相应的maven地址,所有手动引入jar包:

aspose-cells-20.4 - c.jaraspose-words-18.10-jdk16.jar

下载地址:https://download.csdn.net/download/zhuocailing3390/76147206

2、配置lib目录: 在项目的resources目录下,创建lib目录,并且将下载的两个jar包放入其中 在这里插入图片描述 3、引入pom: 引入自定义配置的maven坐标:

com.aspose.cells aspose-cells 20.4 - c system ${project.basedir}/src/main/resources/lib/aspose-cells-20.4 - c.jar com.aspose.words aspose-words words-18.10-jdk16 system ${project.basedir}/src/main/resources/lib/aspose-words-18.10-jdk16.jar 2、配置license

在resources目录下创建license.xml文件,代码如下:

Aspose.Total for Java Aspose.Words for Java Enterprise 20991231 20991231 8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7 sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU= 2、word转pdf

封装工具类:

import com.aspose.words.Document; import com.aspose.words.FontSettings; import com.aspose.words.License; import com.aspose.words.SaveFormat; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * @Author: LiHuaZhi * @Date: 2021/7/13 14:21 * @Description: **/ public class Doc2PdfUtil { /** * 加载授权配置文件 * * @return */ private static boolean getLicense() { boolean result = false; try (InputStream in = Doc2PdfUtil.class.getClassLoader().getResourceAsStream("license.xml")) { // License的包路径必须为com.aspose.words.License License license = new License(); license.setLicense(in); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * doc转pdf * * @param inputStream * @param fileName * @param response * @return */ public static void doc2Pdf(InputStream inputStream,String fileName, HttpServletResponse response) { System.out.println("pdf转换中..."); long old = System.currentTimeMillis(); try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) { // 验证 if (!getLicense()) { throw new RuntimeException("文件转换失败!"); } // 加载字体 FontSettings settings = FontSettings.getDefaultInstance(); settings.setFontsFolder("C:\\Windows\\Fonts", true); LoadOptions loadOptions = new LoadOptions(); loadOptions.setFontSettings(settings); // 也可以直接指定路径 document = new Document(docPath); Document document = new Document(inputStream, loadOptions); // DocumentBuilder builder = new DocumentBuilder(document); // 设置纸张大小 // builder.getPageSetup().setPaperSize(PaperSize.A3); // 设置横向 // builder.getPageSetup().setOrientation(Orientation.LANDSCAPE); document.save(fos, SaveFormat.PDF); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8")); byte[] buffer = fos.toByteArray(); InputStream arrayInputStream = new ByteArrayInputStream(buffer); byte[] buf = new byte[4096]; int len = -1; while ((len = arrayInputStream.read(buf)) != -1) { response.getOutputStream().write(buf, 0, len); } long now = System.currentTimeMillis(); System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("文件转换失败!"); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }

Controller实现:

@RestController @RequestMapping("/test") public class TestController { /** * 导入word文件 * * @param file * @return * @throws Exception */ @RequestMapping("/word") @ResponseBody public void uploadWord(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception { if (file.isEmpty()) { return; } String originalFilename = file.getOriginalFilename(); String fileName = originalFilename.substring(0, originalFilename.lastIndexOf(".")); Doc2PdfUtil.doc2Pdf(file.getInputStream(), fileName, response); } }

postMan测试: 请求接口,比如:http://127.0.0.1:9090/test/word 在这里插入图片描述

3、excel转pdf

封装工具类:

import com.aspose.cells.*; import com.aspose.words.Document; import javax.servlet.http.HttpServletResponse; import java.io.*; public class Excel2PdfUtil { /** * 加载配置文件 * * @return */ private static boolean getLicense() { boolean result = false; try (InputStream in = Excel2PdfUtil.class.getClassLoader() .getResourceAsStream("license.xml")) { // License的包路径必须为com.aspose.cells.License License license = new License(); license.setLicense(in); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * @param inputStream * @param fileName * @param response */ public static void excel2Pdf(InputStream inputStream,String fileName, HttpServletResponse response) { System.out.println("pdf转换中..."); long old = System.currentTimeMillis(); try (ByteArrayOutputStream fos = new ByteArrayOutputStream()) { // 验证 if (!getLicense()) { throw new RuntimeException("文件转换失败!"); } // 设置字体包位置 IndividualFontConfigs configs = new IndividualFontConfigs(); configs.setFontFolder("C:\\Windows\\Fonts", true); LoadOptions loadOptions = new LoadOptions(); loadOptions.setFontConfigs(configs); // 也可以直接指定路径 workbook = new Workbook(docPath, loadOptions); Workbook workbook = new Workbook(inputStream, loadOptions); PdfSaveOptions opts = new PdfSaveOptions(); // 设置excel不换行在pdf显示 // opts.setAllColumnsInOnePagePerSheet(true); // 设置一个sheet在一页pdf opts.setOnePagePerSheet(true); workbook.save(fos, opts); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8")); byte[] buffer = fos.toByteArray(); InputStream arrayInputStream = new ByteArrayInputStream(buffer); byte[] buf = new byte[4096]; int len = -1; while ((len = arrayInputStream.read(buf)) != -1) { response.getOutputStream().write(buf, 0, len); } long now = System.currentTimeMillis(); System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("文件转换失败!"); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }

Controller实现:

@RestController @RequestMapping("/test") public class TestController { /** * 导入excel文件 * * @param file * @return * @throws Exception */ @RequestMapping("/excel") @ResponseBody public void uploadExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception { if (file.isEmpty()) { return; } String originalFilename = file.getOriginalFilename(); String fileName = originalFilename.substring(0, originalFilename.lastIndexOf(".")); Excel2PdfUtil.excel2Pdf(file.getInputStream(), fileName, response); } }

postMan测试: 请求接口,比如:http://127.0.0.1:9090/test/excel 在这里插入图片描述

在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有